package com.itheima.job;

import com.itheima.delaytask.constants.ZKdirConstants;
import com.itheima.delaytask.feign.TaskService;
import com.itheima.utils.ZKSelectMasterUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Created by 传智播客*黑马程序员.
 */
@Component
@Slf4j
public class DelayTaskJob {
    
    @Autowired
    private TaskService taskService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;
    
    @Autowired
    private ZKSelectMasterUtil zkSelectMasterUtil;
    
    @PostConstruct
    public void init(){
        //进行选主
        zkSelectMasterUtil.selectMaster(ZKdirConstants.job_leaderPath);
    }
    
    
    @Scheduled(cron = "*/1 * * * * ?")
    public void refresh(){
        if (zkSelectMasterUtil.checkMaster(ZKdirConstants.job_leaderPath)) {
            taskExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    log.info("job节点{}开始进行定时刷新", LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
                    taskService.refresh();
                }
            });
        }else {
            log.info("从节点备份");
        }
    }
}
